package cn.lichenfei.jfx.music.common;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.lichenfei.jfx.music.common.enums.PlayType;
import cn.lichenfei.jfx.music.common.model.ConfigModel;
import cn.lichenfei.jfx.music.common.utils.AudioDataUtil;
import com.alibaba.fastjson.JSON;

import java.io.File;


/**
 * @author ChenFei
 * @date 2022/5/2
 */
public class Config {

    private static final String USER_HOME = System.getProperty("user.home");
    private static final String ROOT = USER_HOME + "/.cf_music";
    private static final String CONFIG_FILE_NAME = "/config.json";
    private static File configFile = new File(ROOT + CONFIG_FILE_NAME);
    private static ConfigModel configModel;
    //音频文件数据csv文件
    public static final String MUSIC_CSV = ROOT + "/music.list.csv";
    //启动文件
    public static final String START_FILE = ROOT + "/start";

    static {
        Console.log("configPath : {}", configFile.getPath());
        if (!FileUtil.exist(configFile) || !FileUtil.isFile(configFile)) {
            FileUtil.touch(configFile);//文件不在就创建
        }
        String s = FileUtil.readString(configFile, CharsetUtil.CHARSET_UTF_8);
        Console.log("configModel : {}", s);
        if (StrUtil.isBlank(s)) {//如果配置文件为空，第一次创建
            configModel = new ConfigModel();
        } else {
            configModel = JSON.parseObject(s, ConfigModel.class);
        }
    }

    /**
     * 获取最后一次播放的音乐
     *
     * @return
     */
    public static Integer getLastTimeMusic() {
        return configModel.getLastTimeMusic();
    }

    /**
     * 设置最后一次播放的音乐
     *
     * @return
     */
    public static void setLastTimeMusic(Integer val) {
        configModel.setLastTimeMusic(val);
    }


    public static void setVolume(Double volume) {
        configModel.setVolume(volume);
    }

    public static Double getVolume() {
        return configModel.getVolume();
    }

    public static ConfigModel getConfigModel() {
        return configModel;
    }

    public static void setConfigModel(ConfigModel configModel) {
        Config.configModel = configModel;
    }

    /**
     * 存储配置
     */
    public static void storeSetting() {
        Console.log("store: {}", configModel.toString());
        String jsonStr = JSON.toJSONString(configModel);
        jsonStr = JSONUtil.formatJsonStr(jsonStr);
        FileUtil.writeString(jsonStr, configFile, CharsetUtil.CHARSET_UTF_8);
        //
        AudioDataUtil.createCsv(AudioDataUtil.getAll());
    }

    public static void setPlayType(PlayType playType) {
        configModel.setPlayType(playType);
    }
}
